﻿using System.Windows.Input;
using Microsoft.Win32;
using TestBat.IInfrastructure.CSV;
using TestBat.IModels.Domain;
using TestBat.IModels.Models;
using TestBat.IViewModels.Workspaces.Trainees;
using TestBat.ServiceLocator;
using TestBat.ViewModels.Attributes;
using TestBat.ViewModels.Base;
using TestBat.ViewModels.Base.Commands;
using System.Collections.Generic;

namespace TestBat.ViewModels.Workspaces.Trainees
{
    public class TraineeGroupViewModel : ListItemViewModel, ITraineeGroupViewModel
    {
        public TraineeGroupViewModel(ITraineeGroup traineeGroup, ITraineeGroupModel traineeGroupModel)
        {
            this.traineeGroupModel = traineeGroupModel;
            this.traineeGroup = traineeGroup;
        }

        public ITraineeGroup TraineeGroup
        {
            get { return traineeGroup; }
        }

        public ICommand SaveCommand
        {
            get
            {
                return new RelayCommand(e => Save());
            }
        }

        public ICommand ExportCommand
        {
            get
            {
                return new RelayCommand(e => Export());
            }
        }

        private void Export()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = traineeGroup.Name;
            sfd.DefaultExt = ".csv";
            sfd.Filter = "Comma separated values (.csv)|*.csv";

            bool? result = sfd.ShowDialog();

            if (result == true)
            {
                string filename = sfd.FileName;

                ICSVWriter writer = DefaultServiceLocator.Get<ICSVWriter>();

                string[] headers = new string[] { "Username", "Password" };
                IList<string[]> data = new List<string[]>();

                foreach (ITrainee t in traineeGroupModel.GetTrainees(TraineeGroup))
                    data.Add(new string[] { t.Username, t.Password });

                writer.Write(filename, headers, data);
            }
        }

        [BusinessErrorDialog]
        [ValidationErrorDialog]
        private void Save()
        {
            traineeGroupModel.Save(traineeGroup);
        }

        [BusinessErrorDialog]
        public override void OnLostFocus()
        {
            // revert changes
            traineeGroupModel.Revert(traineeGroup);
        }

        private readonly ITraineeGroupModel traineeGroupModel;
        private readonly ITraineeGroup traineeGroup;
    }
}
